package com.xjj.sso.server.rabbitmq;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;

public class QueueConsumer extends EndPoint implements Runnable, Consumer{

	
	
	public QueueConsumer(String endPointName) throws IOException, TimeoutException{
        super(endPointName);       
    }
     
    public void run() {
        try {
        	
        	channel.exchangeDeclare(EXCHANGE_NAME, "topic");
            String queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, EXCHANGE_NAME, endPointName);
        	
            //start consuming messages. Auto acknowledge messages.
        	//第二个参数：是否自动应答 
            channel.basicConsume(queueName,true,this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * Called when consumer is registered.
     */
    public void handleConsumeOk(String consumerTag) {
        System.out.println("Consumer "+consumerTag +" registered");    
    }
 
  
    /**
     * Called when new message is available.
     */
    public void handleDelivery(String consumerTag, Envelope env,
            BasicProperties props, byte[] body) throws IOException {
    	
    	
        System.out.println("Message : "+ new String(body) + " received.");
        
        //发送回执。、
        //channel.basicAck(env.getDeliveryTag(), true);  
    }
    
    
	public void handleCancelOk(String consumerTag) {
		
	}

	public void handleCancel(String consumerTag) throws IOException {
		
	}

	public void handleShutdownSignal(String consumerTag,
			ShutdownSignalException sig) {
		
	}
	public void handleRecoverOk(String consumerTag) {
		
	}
}